<script>
import { deepClone, exportToExcel } from "@/utils/index";
import render from "@/components/render/render.js";
import { getAccessToken } from "@/utils/auth";
import {
  getFormRule,
  getMdColumnsByTableIdUsingGET,
} from "@/api/custom/formDesigner";
import { getLinkData, getRelationData } from "@/api/custom/formPoster";
import SubFormEditDialog from "./SubFormEditDialog.vue";
import TableDataImportDialog from "./TableDataImportDialog.vue";
import { getAutomaticCode, getMainList } from "@/api/custom/autoCoding";
import { calculate } from "./mathOperation.js";
import { download } from "@/utils/index";
import { bindEventScript } from "@/utils/event-script";
//表单校验触发方式配置
const ruleTrigger = {
  "el-input": "blur",
  "el-input-number": "blur",
  "el-number": "blur",
  "my-select": "change",
  "my-radio-group": "change",
  "my-checkbox-group": "change",
  "el-tree-select": "change",
  "el-cascader": "change",
  "my-cascader": "change",
  "my-region": "blur",
  "el-time-picker": "change",
  "el-date-picker": "change",
  "el-rate": "change",
  getMapPoint: "change",
  PostSelection: "blur",
  UsersSelector: "blur",
  DepartmentSelection: "blur",
  Steps: "blur",
  pictureSelect: "change",
};
let encodeCode = "";
let encodeobj = {}; //编码组件
let objMonitor = {}; //monitorMap构成数组
let objMonitorCopy = {}; //monitorMap构成数组
let codingFields = []; // 最终展示的编码字段组成的数组
let isHasCode = false; //是否存在编码字段
let originAllData = {}; //编辑界面初始数据
let listenField = ""; //被监听字段名
//列布局、行布局组件渲染
const layouts = {
  colFormItem(h, scheme) {
    const config = scheme.__config__;
    const listeners = buildListeners.call(this, scheme);
    let child = renderChildren.apply(this, arguments);
    let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null;
    if (config.showLabel === false) labelWidth = "0";
    if (scheme.hide === true) {
      //根据表单规则，隐藏该组件
      return null;
    }
    if (this.formConfCopy.disabled || this.status === "view") {
      //禁用富文本
      if (config.tag === "tinymce") {
        scheme.readonly = true;
        scheme.disabled = true;
      }
      if (config.tag === "signature") {
        scheme.disabled = true;
      }
      if (config.tag === "el-upload") {
        scheme.disabled = true;
      }
    }
    let isShowDesc = [
      "Subform",
      "TitleLine",
      "el-tabs",
      "el-collapse",
      "Steps",
    ].includes(config.tag);
    if (config.bianma) {
      scheme.disabled = true;
      encodeobj = scheme; //编码组件
    }
    if (config.tag === "Steps") {
      const slotOptions = scheme.__slot__.options;
      const _this = this;
      return (
        <el-col
          span={config.span}
          nativeOnClick={(event) => {
            event.stopPropagation();
          }}
        >
          <render
            key={config.renderKey}
            conf={scheme}
            onInput={(event) => {
              _this.$set(config, "defaultValue", event);
            }}
            onJumpStep={(idx) => {
              _this.jumpStep(scheme, idx);
            }}
          ></render>
          {child[config.active - 1]}
        </el-col>
      );
    }
    return (
      <el-col span={config.span}>
        <el-form-item
          label-width={labelWidth}
          prop={scheme.__vModel__}
          label={config.showLabel ? config.label : ""}
        >
          {this.formConf.labelDescriptionPosition === "icon" && !isShowDesc && (
            <span slot="label">
              {config.showLabel ? config.label : ""}
              {config.descriptionMessage ? (
                <el-tooltip content={config.descriptionMessage} placement="top">
                  <i class="el-icon-question" style={{ color: "#cacad3" }}></i>
                </el-tooltip>
              ) : (
                ""
              )}
            </span>
          )}
          <render conf={scheme} on={listeners} child={child} />
          <div style={{ color: "#909399" }}>
            {this.formConf.labelDescriptionPosition === "button" &&
              !isShowDesc &&
              config.descriptionMessage}
          </div>
        </el-form-item>
      </el-col>
    );
  },
  rowFormItem(h, scheme) {
    let child = renderChildren.apply(this, arguments);
    if (scheme.type === "flex") {
      child = (
        <el-row
          type={scheme.type}
          justify={scheme.justify}
          align={scheme.align}
        >
          {child}
        </el-row>
      );
    }
    const config = scheme.__config__;

    // 选项卡/折叠面板
    if (
      config.tag === "el-tabs" ||
      config.tag === "el-collapse" ||
      config.tag === "Steps"
    ) {
      return (
        <el-col span={config.span}>
          <el-row gutter={config.gutter}>
            <render child={child} key={config.renderKey} conf={scheme} />
          </el-row>
        </el-col>
      );
    }
    // 卡片布局
    if (config.tag === "el-card") {
      return (
        <el-col span={config.span}>
          <el-row gutter={config.gutter}>
            {config.tag === "el-card" && (
              <div style="line-height: '36px';font-size: '14px';font-weight: 600;margin-bottom: 10px;margin-left: '15px';">
                {config.label}
              </div>
            )}
            {config.shadow == "never" && (
              <render
                child={child}
                key={config.renderKey}
                conf={scheme}
                style="box-shadow:0px 0px 0px 0px rgba(0,0,0,0)"
              />
            )}
            {config.shadow == "hover" && (
              <render
                child={child}
                key={config.renderKey}
                conf={scheme}
                class="cardhover"
              />
            )}
            {config.shadow == "always" && (
              <render
                child={child}
                key={config.renderKey}
                conf={scheme}
                style="box-shadow:0 2px 12px 0 rgba(0,0,0,.1)"
              />
            )}
          </el-row>
        </el-col>
      );
    }
    if (config.tag === "Subform") {
      const sortField = scheme.__config__.sortField;
      let children = deepClone(config.children[0].__config__.children);
      //    let children = this.makeTable(config.renderKey);
      const optionBtnNum = scheme.options.filter(
        (item) => item.position !== "table"
      ).length;
      const tableData = scheme.__config__.isPage
        ? scheme.tableData.slice(
            (config.curPage - 1) * Number(config.pageSize),
            config.curPage * Number(config.pageSize)
          )
        : scheme.tableData;
      const style =
        "display:flex;height: 40px;line-height: 40px;justify-content: space-between;margin: 5px 0px;";
      let tableFormInfo = {};
      if (!tableFormInfo.tableDataForm) {
        tableFormInfo.tableDataForm = [];
      }
      tableFormInfo.tableDataForm = [...tableData];
      return (
        <div>
          <el-col style="border-radius: 10px;padding:0px 10px 10px 10px;margin: 10px 0px">
            {
              // 表格按钮区 添加/删除/复制/上移/下移/导入/导出/编辑
              <div style={style}>
                <div style="font-weight: 600;">{config.label}</div>
                <div>
                  {scheme.options
                    .filter((item) => item.position === "table")
                    .map((item) => (
                      <el-button
                        type={item.type}
                        size="mini"
                        onClick={() => {
                          // this.$emit(item.command, this.mulArr, config.renderKey)
                          this.btnFunc(
                            item.command,
                            config.renderKey,
                            this.mulArr,
                            config.editType
                          );
                        }}
                      >
                        {item.label}
                      </el-button>
                    ))}
                </div>
              </div>
            }
            {
              <el-form
                props={{ model: tableFormInfo }}
                ref={scheme.__config__.renderKey}
              >
                <el-table
                  data={tableFormInfo.tableDataForm}
                  border={config.formBorder}
                  stripe
                  highlight-current-row
                  onSelect={this.handleSelectionChange}
                  on-select-all={this.handleSelectionChange}
                >
                  {
                    // 多选
                    <el-table-column
                      type="selection"
                      width="55"
                      align="center"
                      fixed
                    ></el-table-column>
                  }
                  {config.showNum && !this.hideData[0]?.hide && (
                    <el-table-column
                      {...{
                        scopedSlots: {
                          // 序号，render函数内使用scope写法
                          default: (scope) => {
                            return scope.$index + 1;
                          },
                        },
                      }}
                      width={config.numWidth}
                      label={config.numLabel}
                      align="center"
                    ></el-table-column>
                  )}
                  {
                    // 表格列以及数据渲染
                    children.map((item, index) => {
                      const indexHide = config.showNum ? index + 1 : index;
                      const dom = (
                        <el-table-column
                          width={config.labelIsShow && config.columnWidth}
                          key={index}
                          column-key={index + ""}
                          prop={item.__vModel__}
                          // 左侧固定列与右侧固定列
                          fixed={
                            (index < config.leftCol && "left") ||
                            (config.rightCol + index + 1 > children.length &&
                              "right")
                          }
                          align="center"
                          min-width="200"
                          sortable={
                            sortField === item.__vModel__ ? true : false
                          }
                          {...{
                            scopedSlots: {
                              // render函数内使用scope写法
                              default: (scope) => {
                                item.__config__.defaultValue =
                                  scope.row[item.__vModel__];
                                const newItem = {
                                  ...item,
                                  __config__: {
                                    ...item.__config__,
                                    defaultValue: scope.row[item.__vModel__],
                                  },
                                };
                                const dom = (
                                  <el-form-item
                                    prop={`tableDataForm.${scope.$index}.${newItem.__vModel__}`}
                                    rules={[
                                      ...newItem.__config__.regList,
                                      {
                                        required: item.__config__.required,
                                        message:
                                          "请输入" + item.__config__.label,
                                        trigger: "change",
                                      },
                                    ]}
                                    style="margin-top:20px"
                                    labelWidth="0"
                                  >
                                    <render
                                      key={newItem.__config__.renderKey}
                                      conf={newItem}
                                      // 多选框组 event 返回值为布尔值，导致多选出错(未解决)
                                      onInput={(event) => {
                                        // 更改配置数据
                                        this.$set(
                                          item.__config__,
                                          "defaultValue",
                                          event
                                        );
                                        // 更改配置数据tableData数据，不然数据丢失
                                        this.updateTableData({
                                          index: scope?.$index,
                                          compObj: item,
                                          value: event,
                                          renderKey: config.renderKey,
                                        });
                                      }}
                                      onChange={(event) => {
                                        if (item.change) {
                                          // this.$set(item.__config__, 'defaultValue', event)
                                          bindEventScript.call(
                                            this,
                                            "",
                                            "",
                                            item.change
                                          );
                                        }
                                      }}
                                      onBlur={(event) => {
                                        if (item.blur) {
                                          bindEventScript.call(
                                            this,
                                            "",
                                            "",
                                            item.blur
                                          );
                                        }
                                      }}
                                    />
                                  </el-form-item>
                                );
                                return config.componentBorder ? (
                                  dom
                                ) : scope.row.showComp ? (
                                  dom
                                ) : (
                                  <div>{item.__config__.defaultValue}</div>
                                );
                              },
                            },
                          }}
                          // 必填格式表头
                          render-header={(h, { column, $index }) => {
                            return item.__config__.required
                              ? h("div", [
                                  h(
                                    "span",
                                    {
                                      style: {
                                        color: "#ff4949",
                                        marginRight: "5px",
                                      },
                                    },
                                    "*"
                                  ),
                                  h("span", item.__config__.label),
                                ])
                              : h("div", [h("span", item.__config__.label)]);
                          }}
                        ></el-table-column>
                      );
                      return config.renderKey ===
                        this.hideData[indexHide]?.renderKey
                        ? !this.hideData[indexHide]?.hide && dom
                        : dom;
                    })
                  }
                  {
                    // 表格操作列
                    optionBtnNum > 0 ? (
                      <el-table-column
                        width={
                          optionBtnNum === 1 ? "80px" : optionBtnNum * 60 + "px"
                        }
                        {...{
                          scopedSlots: {
                            default: (scope) => {
                              const btn = scheme.options.filter(
                                (item) => item.position !== "table"
                              );
                              return btn.map((item, index) => {
                                return (
                                  <el-tooltip
                                    effect="light"
                                    content={item.label}
                                    placement="top"
                                  >
                                    <el-button
                                      type={item.type}
                                      onClick={() => {
                                        // this.$emit(item.command, scope, config.renderKey, config.editType)
                                        this.optionBtnFunc(
                                          item.command,
                                          scope,
                                          config.renderKey,
                                          config.editType
                                        );
                                      }}
                                      key={index}
                                      size="mini"
                                      icon={item.iconType}
                                    ></el-button>
                                  </el-tooltip>
                                );
                              });
                            },
                          },
                        }}
                        align="center"
                        fixed="right"
                        render-header={(h, { column, $index }) => {
                          return config.showCustomColumn
                            ? h("div", [
                                h("span", "操作"),
                                h("i", {
                                  class: "el-icon-s-operation",
                                  style: "margin-left:5px;cursor:pointer",
                                  on: {
                                    click: () =>
                                      this.explicit(config.renderKey), // 显隐
                                  },
                                }),
                              ])
                            : h("div", [h("span", "操作")]);
                        }}
                      ></el-table-column>
                    ) : null
                  }
                </el-table>
              </el-form>
            }
          </el-col>
          {config.isPage && (
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              total={scheme.tableData.length}
              page-size={Number(config.pageSize)}
              page-sizes={[10, 20, 30, 50]}
              current-page={config.curPage}
              style="float: right;margin-bottom:10px"
              on-current-change={(curPage, renderKey) =>
                this.curPageChange(curPage, config.renderKey)
              }
              on-size-change={(pageSize) =>
                this.curSizeChange(pageSize, config.renderKey)
              }
            ></el-pagination>
          )}
        </div>
      );
    }
    return (
      <el-col span={scheme.span}>
        <el-row gutter={scheme.gutter}>{child}</el-row>
      </el-col>
    );
  },
};
//渲染表单
function renderFrom(h) {
  const { formConfCopy, status } = this;
  return (
    <el-row gutter={formConfCopy.gutter}>
      <el-form
        size={formConfCopy.size}
        label-position={formConfCopy.labelPosition}
        disabled={formConfCopy.disabled}
        label-width={`${formConfCopy.labelWidth}px`}
        ref={formConfCopy.formRef}
        // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
        props={{ model: this[formConfCopy.formModel] }}
        rules={this[formConfCopy.formRules]}
      >
        {renderFormItem.call(this, h, this.formConfCopy.fields)}
        {status !== "view" && formConfCopy.formBtns && formBtns.call(this, h)}
      </el-form>
    </el-row>
  );
}
//表单按钮
function formBtns(h) {
  // return <el-col>
  //   <el-form-item size="large" style="textAlign:center;marginRight:100px;">
  //     <el-button type="primary" onClick={this.submitForm} size="small">提交</el-button>
  //     <el-button onClick={this.resetForm} size="small">重置</el-button>
  //   </el-form-item>
  // </el-col>

  // return <el-col>
  //   <el-form-item size="large" style="textAlign:center;marginRight:100px;">
  //     <el-button type="primary" onClick={this.submitForm} size="small">提交</el-button>
  //   </el-form-item>
  // </el-col>

  //按钮自定义配置
  const { formConfCopy } = this;
  return (
    <el-col>
      <div
        style={{ "text-align": formConfCopy.btnPosition, paddingTop: "20px" }}
      >
        {Array.isArray(formConfCopy.btnConfig) ? (
          formConfCopy.btnConfig
            .filter((item) => item.label !== "保存")
            .map((item) => {
              if (item.checked) {
                return (
                  <el-button
                    type={item.type}
                    onclick={this[`${item.click}Form`]}
                    size="small"
                  >
                    {item.text}
                  </el-button>
                );
              } else {
                return null;
              }
            })
        ) : (
          <div style={{ textAlign: "center" }}>
            <el-button type="primary" onclick={this.submitForm} size="small">
              确认
            </el-button>
            <el-button type="info" onclick={this.cancelForm} size="small">
              取消
            </el-button>
          </div>
        )}
      </div>
    </el-col>
  );
}

//渲染组件
function renderFormItem(h, elementList) {
  return elementList.map((scheme) => {
    const config = scheme.__config__;
    const layout = layouts[config.layout];
    if (layout) {
      return layout.call(this, h, scheme);
    }
    throw new Error(`没有与${config.layout}匹配的layout`);
  });
}
//渲染子组件
function renderChildren(h, scheme) {
  const config = scheme.__config__;
  if (!Array.isArray(config.children)) return null;
  return renderFormItem.call(this, h, config.children);
}
//赋默认值
function setValue(event, config, scheme) {
  if (event) {
    // 数据联动
    if (this.linkNameMap.has(scheme.__vModel__)) {
      this.getLinkDataFunc(scheme.__vModel__, event);
    }
    // 关联数据
    this.relatedDataFunc(scheme, event);
  }
  this.$set(config, "defaultValue", event);
  this.$set(this[this.formConf.formModel], scheme.__vModel__, event);
  // 公式计算
  this.calculateFormula(this.formConfCopy.fields, event);
}

//监听组件值change事件，查询表单规则结果
function setShowHide() {
  if (this.formConfCopy.ruleConfig && this.formConfCopy.ruleConfig.length > 0) {
    this.ruleConfig.forEach((cur, index) => {
      cur.formList = [];
      Object.keys(this[this.formConf.formModel]).forEach((key) => {
        //获取当前表单各个字段的值
        cur.formList.push({
          filedName: key,
          value: Array.isArray(this[this.formConf.formModel][key])
            ? this[this.formConf.formModel][key].join(",")
            : this[this.formConf.formModel][key],
        });
      });
    });
    getFormRule(this.ruleConfig)
      .then((res) => {
        if (res.code === 0) {
          if (res.data !== null && res.data !== "不符合规则") {
            //符合规则
            this.displayFields = res.data.dispalyField?.split(",") || [];
            this.changeShowHide(this.formConfCopy.fields, this.displayFields);
          }
          //  else{ //不符合规则
          //   this.displayFields = []
          //   this.changeShowHide(this.formConfCopy.fields,this.displayFields)
          // }
        }
      })
      .catch((e) => console.log(e));
  }
}
//绑定事件监听器
function buildListeners(scheme) {
  let _this = this;
  const config = scheme.__config__;
  const methods = this.formConf.__methods__ || {};
  const listeners = {};

  // 给__methods__中的方法绑定this和event
  Object.keys(methods).forEach((key) => {
    listeners[key] = (event) => methods[key].call(this, event);
  });

  // 响应 render.js 中的 vModel $emit('input', val)
  listeners.input = (event) => setValue.call(this, event, config, scheme);
  // 响应 render.js 中的 vModel $emit('change', val)
  listeners.change = (event) => {
    if (this.formConfCopy.fields.length > 0) {
      this.formConfCopy.fields.forEach((item, index) => {
        if (item.__config__.tag === "Subform" && item.__config__.valueConfig) {
          //如果是子表单 且 这个子表单跟某个级联 或者 下拉框关联
          this.setSubformData(item, scheme);
        }
        if (item.__config__.tag === "signature") {
          //手写签名 fix: 表单管理，有手写签名的时候，直接提交没点确定，有请输入手写签名的校验，点确定 校验不消失的bug
          if (item.__config__.defaultValue) {
            //如果有值
            this.$refs[this.formConf.formRef]?.clearValidate(item.__vModel__);
          }
        }
        if (item.__config__.tag === "my-radio-group") {
          //单选 fix:表单管理，第一次点击 提示单选框组不能为空的bug
          if (item.__config__.defaultValue) {
            //如果有值
            this.$refs[this.formConf.formRef]?.clearValidate(item.__vModel__);
          }
        }
      });
    }
    if (isHasCode) {
      //有编码字段时才会走接口
      this.getCodeData(scheme, config, event);
    }
    setValue.call(this, event, config, scheme);
    setShowHide.call(this);
    if (scheme.change) {
      bindEventScript.call(_this, "", "", scheme.change);
    }
  };
  // 响应 render.js 中的 vModel $emit('blur', val)
  listeners.blur = (event) => {
    if (scheme.blur) {
      bindEventScript.call(_this, "", "", scheme.blur);
    }
  };
  return listeners;
}
const basicTypes = [
  "number",
  "color",
  "rate",
  "date",
  "time",
  "password",
  "textArea",
  "input",
  "slider",
  "place",
  "numbers",
]; //从数据库中获取值无需处理
export default {
  name: "parser",
  components: {
    render,
    SubFormEditDialog,
    TableDataImportDialog,
  },
  props: {
    formConf: {
      //表单组件、表单属性配置对象
      type: Object,
      required: true,
    },
    status: {
      //状态值，新增/编辑/查看
      type: String,
      required: true,
    },
    tableName: {
      type: String,
      default: "",
      required: false,
    },
    originData: {
      //表单初始数据，用于数据回显
      type: Object,
      required: true,
    },
    showHideData: {
      type: Array,
      // required: true
    },
    codeReshow: {
      type: Object,
      required: true,
    },
  },
  computed: {
    hideData() {
      return this.showHideData
        ? JSON.parse(JSON.stringify(this.showHideData))
        : [];
    },
  },
  data() {
    const data = {
      // encodeCode:'',
      // encodeobj:{},//编码组件
      // objMonitor:{},//monitorMap构成数组
      // objMonitorCopy:{}, //monitorMap构成数组
      // codingFields:[],// 最终展示的编码字段组成的数组
      // isHasCode:false,//是否存在编码字段
      tableAddFlag: "",
      formConfCopy: deepClone(this.formConf),
      [this.formConf.formModel]: {},
      [this.formConf.formRules]: {},
      mulArr: [],
      ruleConfig: [], //表单规则配置
      displayFields: [], //表单规则--隐藏字段
      redioValue: "",
      // showHideData:[],
      curRowCompData: [],
      curRowCompConfig: {},
      curRowNum: -1,
      tableIndex: "",
      tableTagIcons: [], // 子表单导出功能使用
      curRenderKey: "", //子表单导入按钮使用
      showImportDialog: false, // 子表单导入按钮 （复用excel导入组件）
      showSubDialog: false, // 子表单编辑时 弹窗模式
      subFormId: "",
      curformName: "", // 当前表单(子表单)名称
      originDataCopy: deepClone(this.originData),
      linkNameMap: new Set(), // 存储 存在联动关系字段
      linkObjList: [], // 存储联动对象数据
      filterTag: [
        "Subform",
        "el-tabs",
        "TitleLine",
        "TitleLine",
        "Steps",
        "el-switch",
        "el-collapse",
        "el-card",
        "UsersSelector",
        "DepartmentSelection",
        "PostSelection",
        "signature",
      ],
    };
    this.bindUploadSuccess(data.formConfCopy.fields, this.formConf.formModel); //为el-upload上传组件绑定on-success、on-remove事件
    this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel]); //初始化表单数据
    data.formConfCopy.fields.forEach((item, index) => {
      originAllData[item.__vModel__] = item.__config__.defaultValue;
    });
    this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules]); //构建表单校验规则
    this.initRuleConfig(
      data.formConfCopy,
      data.ruleConfig,
      data[this.formConf.formModel]
    ); //初始化表单规则配置
    return data;
  },
  created() {
    this.loopSetObj(this.formConfCopy.fields);

    const codingList = this.formConfCopy.fields.filter((item) => {
      return item.__config__.tagIcon === "coding";
    }); //过滤编码组件
    if (codingList && codingList.length > 0) {
      // 有编码组件 开启
      if (this.status === "add") {
        objMonitor = {};
      } else {
        objMonitor = objMonitorCopy;
      }
      //获取被监听组件
      getMainList({ pageNo: 1, pageSize: 49, encodeName: "" }).then((res) => {
        if (res && res.code === 0) {
          let strarr = res.data.list.filter((val) => {
            return val.id == encodeCode;
          });
          codingFields = strarr[0] ? strarr[0].applyFieldList : [];
        }
      });
      isHasCode = true;
    } else {
      isHasCode = false;
    }

    if (this.formConf?.formJs?.onLoad) {
      bindEventScript.call(this, "", "", this.formConf.formJs.onLoad);
    }
    if (this.status === "add") {
      //新增时清空子表单数据
      if (this.formConfCopy.fields.length > 0) {
        console.log(this.formConfCopy.fields);
        this.formConfCopy.fields.forEach((item, index) => {
          if (item.__config__.tag === "Subform") {
            //如果是子表单
            item.tableData = [];
          }
        });
      }
    }

    // this.formConfCopy.fields.map((item,index)=>{
    //   if(item.__config__.tagIcon === 'coding'){
    //     isHasCode = true
    //   }
    // })
  },
  methods: {
    getCodeData(scheme, config, event) {
      //多个关联字段的情况
      if (codingFields.length > 0) {
        codingFields.map((item, index) => {
          if (item.applyField === scheme.__vModel__) {
            objMonitor[item.id] = config.defaultValue;
            listenField = item.applyField;
          }
        });
      }
      if (scheme.__vModel__ === listenField) {
        {
          /* if(originAllData[listenField] === event){
          setValue.call(this, originAllData[listenField], encodeobj.__config__, encodeobj)
        }else{ */
        }
        let params = {
          tableName: this.tableName,
          column: encodeobj.__vModel__,
          encodeId: encodeobj.rulesSelectValue,
          monitorMap: objMonitor,
        };
        getAutomaticCode(params).then((res) => {
          if (res.code === 0) {
            encodeobj.__config__.defaultValue =
              res.data.storeData === " " ? " " : res.data.storeData; //展示隐藏值
            encodeobj.__slot__.options = [
              {
                label: res.data.showData,
                value: res.data.storeData,
              },
            ];
            encodeobj.options = [
              {
                label: res.data.showData,
                value: res.data.storeData,
              },
            ];
            encodeobj.value = encodeobj.__config__.defaultValue;
            this.$set(
              this[this.formConf.formModel],
              encodeobj.__vModel__,
              encodeobj.__config__.defaultValue
            );
          }
        });
        {
          /* }         */
        }
      }
    },
    // async getCodeData(scheme,config){
    //   let str = await getMainList({pageNo:1,pageSize:49,encodeName:''});
    //   if(str && str.code===0){
    //     //避免没有编码组件的情况
    //     let strarr = str.data.list.filter(val=>{
    //       return val.id == encodeCode
    //     })
    //     str = strarr[0]?strarr[0].applyFieldList[0]:''
    //     if(scheme.__vModel__ === str){
    //       let params ={
    //         tableName:this.tableName,
    //         column:encodeobj.__vModel__,
    //         encodeId:encodeobj.rulesSelectValue,
    //         monitorMap:{}
    //       }
    //       params.monitorMap[str] = config.defaultValue;
    //       let encodestr = await getAutomaticCode(params);  //获取显示值和隐藏值
    //       encodeobj.__config__.defaultValue = encodestr.data.showData === "null"?' ':encodestr.data.showData; //展示隐藏值
    //       this.$set(this[this.formConf.formModel], encodeobj.__vModel__, encodeobj.__config__.defaultValue)
    //     }
    //   }
    // },
    toUp(str) {
      let newStr = "";
      let arr = str.split("_"); //先用字符串分割成数组

      arr.forEach((item, index) => {
        if (index > 0) {
          return (newStr += item.replace(item[0], item[0].toUpperCase()));
        } else {
          return (newStr += item);
        }
      });
      return newStr;
    },
    nameTo_(object) {
      let regObj = new RegExp("([A-Z]+)", "g");
      for (let i in object) {
        if (object.hasOwnProperty(i)) {
          let temp = object[i];
          if (regObj.test(i.toString())) {
            temp = object[
              i.replace(regObj, function (result) {
                return "_" + result.toLowerCase();
              })
            ] = object[i];
            delete object[i];
          }
          if (
            typeof temp === "object" ||
            Object.prototype.toString.call(temp) === "[object Array]"
          ) {
            this.nameTo_(temp);
          }
        }
      }
      return object;
    },
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    },
    setSubformData(val, data) {
      if (val.__config__.valueConfig.__vModel__ == data.__vModel__) {
        // 子表单对应的 下拉框 或者  级联
        let arr = [],
          arr1 = [],
          arr2 = [],
          arrDif = []; //arr -- label  arr1 -field字段
        val.__config__.children[0].__config__.children.filter((_) =>
          arr.push(_.__config__.label)
        );
        val.__config__.children[0].__config__.children.filter((_) =>
          arr1.push(_.__vModel__)
        );
        let selectData = this.formConfCopy.fields.filter(
          (_) => _.__vModel__ == val.__config__.valueConfig.__vModel__
        );
        let tableId = this.setDefaultValue(
          selectData[0].__config__.defaultValue
        );
        arr1.forEach((item) => {
          arr2.push(this.toUp(item));
        });
        if (!selectData[0].__config__.defaultValue.length) {
          val.tableData = [];
          return;
        } else {
          getMdColumnsByTableIdUsingGET(tableId).then((res) => {
            if (res.data.length > 0) {
              let keys = Object.keys(res && res.data && res.data[0]);
              let commonLis = arr2.filter((item) => keys.indexOf(item) > -1);
              this.nameTo_(res.data);
              let different = this.getArrDifference(arr2, commonLis); //取不同项
              different.forEach((item) => {
                arrDif.push(item.replace(/([A-Z])/g, "_$1").toLowerCase());
              });
              if (commonLis.length == 0) {
                // 匹配不是 数据为 []
                val.tableData = [];
              } else {
                arrDif.map((i) => {
                  res.data.forEach((item, index) => {
                    item.showComp = true;
                    item[i] = "";
                  });
                });
                val.tableData = [...res.data];
              }
            } else {
              val.tableData = [];
            }
          });
        }
      }
    },
    setDefaultValue(val) {
      if (Array.isArray(val)) {
        return val.join(",");
      }
      // if (['string', 'number'].indexOf(typeof val) > -1) {
      //   return val
      // }
      if (typeof val === "boolean") {
        return `${val}`;
      }
      return val;
    },
    // 公式计算(不包括子表单)
    calculateFormula(list, value, newfield) {
      list.forEach((item) => {
        if (
          item.__config__.tag === "el-card" ||
          item.__config__.tag === "el-tabs" ||
          item.__config__.tag === "Steps" ||
          item.__config__.tag === "el-collapse"
        ) {
          //布局组件，遍历内部子组件
          item.__config__.children.forEach((c) => {
            this.calculateFormula(c.__config__.children, value, newfield);
          });
        } else {
          let editorStr = item.__config__.formulaStr;
          if (editorStr) {
            const signList = editorStr.match(/\$.*?\#/g);
            if (signList?.length > 0) {
              const otherStr = editorStr.split(/\$.*?\#/g);
              let exsitFlag = false;
              let valueList = [];
              signList.forEach((signField) => {
                // 取出字段field
                let fieldValue;
                const field = signField.slice(1, signField.length - 1).trim();
                if (
                  this[this.formConf.formModel][field] &&
                  this[this.formConf.formModel][field] !== "-"
                ) {
                  fieldValue = this[this.formConf.formModel][field];
                } else {
                  fieldValue = 0;
                }
                valueList.push(fieldValue);
                // 判断当前改变的组件字段是否存在于 其他组件配置的公式里，如果存在，则需要在配置公式的组件上都要相应计算公式
                // if (field === scheme.__vModel__) {
                //     exsitFlag = true
                // }
              });
              editorStr = this.joinStr(otherStr, valueList);
              // if (exsitFlag) {
              //     // 拼接公式
              // }
            }
            // 调用计算
            let finallyValue = calculate(editorStr);
            if (item.__config__.numberType === "percentage") {
              //如果是百分比 需要*100
              finallyValue = finallyValue * 100;
            }
            // 塞值
            this.setFormParams({
              key: item.__vModel__,
              value: finallyValue,
            });
          }
        }
      });
    },

    // 拼接字符串
    joinStr(strList, valueList) {
      // 将strList 与 valueList 数组合并
      let newStr = "";
      strList.forEach((other, index) => {
        newStr = newStr + other;
        if (valueList[index] !== undefined) {
          newStr = newStr + valueList[index];
        }
      });
      return newStr;
    },
    // 点击标题跳转
    jumpStep(currentItem, stepIdx) {
      const curCompIdx = this.formConfCopy.fields.findIndex((comp) => {
        return comp.__vModel__ === currentItem.__vModel__;
      });
      this.$set(
        this.formConfCopy.fields[curCompIdx].__config__,
        "active",
        stepIdx + 1
      );
      this.formConfCopy.fields.forEach((comp) => {
        if (comp.__config__.tag === "Steps") {
          if(stepIdx === comp.__slot__.options.length -1){
            this.$emit('change',true) //显示完成
          } else{
            this.$emit('change',false)
          }
        }
      })
     
    },
    // 点击按钮跳转
    jumpBtnStep(flag) {
      this.formConfCopy.fields.forEach((comp) => {
        if (comp.__config__.tag === "Steps") {
          if (
            flag === "up" &&
            comp.__config__.active < comp.__slot__.options.length
          ) {
            this.$refs[this.formConf.formRef].validate((valid) => {
                if (!valid) return false;
                this.$set(comp.__config__, "active", comp.__config__.active + 1);
            })
          }
          if (flag === "down" && comp.__config__.active > 1) {
            this.$refs[this.formConf.formRef].clearValidate()
            this.$set(comp.__config__, "active", comp.__config__.active - 1);
          }
          if(flag === "up" && comp.__config__.active === comp.__slot__.options.length){
            this.$emit('change',true)
          }else{
            this.$emit('change',false)
          }
        }
      });
    },
    // 联动数据触发方法
    getLinkDataFunc(fieldId, curVal) {
      const objList = [];
      this.linkObjList.forEach((item) => {
        let obj = {};
        if (item.curParams === fieldId) {
          obj = {
            linkName: item.linkName,
            linkValueName: item.linkValueName,
            tableName: item.tableName,
            curValue:  Array.isArray(curVal) ? curVal.toString() : curVal,
            returnField: item.returnField,
          };
          objList.push(obj);
        }
      });
      // 联动数据
      getLinkData(objList).then((rsp) => {
        if (rsp.code === 0) {
          if (Array.isArray(rsp.data)) {
            rsp.data.forEach((valueObj) => {
              this.setFormParams(valueObj);
            });
          }
        }
      });
    },
    // 关联数据触发方法
    relatedDataFunc(scheme, curVal) {
      const fieldId = scheme.__vModel__;
      const relatedObj = scheme.__config__.relatedData;
      if (
        relatedObj &&
        JSON.stringify(relatedObj) !== "{}" &&
        relatedObj.curParams === fieldId
      ) {
        const tempObj = {
          curValue: Array.isArray(curVal) ? curVal.toString() : curVal,
          linkName: relatedObj.linkName,
          tableName: relatedObj.tableName,
          sysRelationDataList: relatedObj.sysRelationDataList,
        };
        getRelationData(tempObj).then((rsp) => {
          if (rsp.code === 0) {
            if (Array.isArray(rsp.data)) {
              rsp.data.forEach((valueObj) => {
                this.setFormParams(valueObj);
              });
            }
          }
        });
      }
    },
    // 表单字段赋值(不包括子表单)
    setFormParams(valueObj) {
      this.loopSearch(this.formConfCopy.fields, valueObj);
    },
    loopSearch(list, valueObj, flag, rowIndex) {
      list.forEach((item) => {
        if (
          item.__config__.tag === "el-card" ||
          item.__config__.tag === "el-tabs" ||
          item.__config__.tag === "Steps" ||
          item.__config__.tag === "el-collapse"
        ) {
          //布局组件，遍历内部子组件
          item.__config__.children.forEach((c) => {
            this.loopSearch(c.__config__.children, valueObj);
          });
        }
        if (item.__config__.tag === "Subform") {
          const tableCompList = item.__config__.children[0].__config__.children;
          const flagObj = tableCompList.find((cur) => {
            return cur.__vModel__ === valueObj.key;
          });
          if (flagObj) {
            if (item.tableData.length === 0) {
              this.btnFunc(
                "insert",
                item.__config__.renderKey,
                [],
                item.__config__.editType
              );
            }
            this.$nextTick(() => {
              // 转换成前台需要的值
              let tempVal = this.setFormatValue(
                valueObj.value,
                flagObj.type,
                flagObj.__config__.tagIcon,
                flagObj.options
              );
              item.tableData.forEach((inside) => {
                this.$set(inside, valueObj.key, tempVal);
              });
            });
          }
        } else {
          let tempVal = "";
          if (item.__vModel__ === valueObj.key) {
            // 转换成前台需要的值
            tempVal = this.setFormatValue(
              valueObj.value,
              item.type,
              item.__config__.tagIcon,
              item.options
            );
            // 强制更新数据渲染表单
            this.$set(item.__config__, "defaultValue", tempVal);
            // 表单校验塞值
            this.$set(
              this[this.formConf.formModel],
              item.__vModel__,
              item.__config__.defaultValue
            );
          }
        }
      });
    },
    // 存储存在联动数据的字段
    loopSetObj(list) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (
          ["el-card", "el-tabs", "Steps", "el-collapse"].includes(
            item.__config__.tag
          )
        ) {
          //布局组件，遍历内部子组件
          item.__config__.children.forEach((c) => {
            this.loopSetObj(c.__config__.children);
          });
        } else if (item.__config__.tag === "Subform") {
          const tableCompList = item.__config__.children[0].__config__.children;
          for (let x = 0; x < tableCompList.length; x++) {
            const newComp = tableCompList[x];
            this.existLinkName(newComp);
          }
        } else {
          this.existLinkName(item);
        }
      }
    },
    existLinkName(compItem) {
      if (
        !this.filterTag.includes(compItem.__config__.tag) &&
        compItem.__config__.defaultSelect === "linkData" &&
        JSON.stringify(compItem.__config__.linkObj) !== "{}"
      ) {
        // 存在联动关系的字段
        this.linkNameMap.add(compItem.__config__.linkObj.curParams);
        // 按字段来存储当前表单存在联动关系的数据
        this.linkObjList.push(compItem.__config__.linkObj);
      }
    },
    //将数据库存储类型转为组件数据类型
    setFormatValue(data, format, tag, options) {
      if (!data) {
        //空数据
        return data;
      }
      if (format === "datetime") {
        return this.getDateTime(data);
      }
      if (tag === "upload") {
        if (this.isJson(data)) {
          return JSON.parse(data);
        } else {
          return [];
        }
      }
      if (basicTypes.includes(tag)) {
        return data;
      }
      if (tag === "time-range" || tag === "date-range" || tag === "checkbox") {
        return data.split(",");
      }
      if (tag === "switch") {
        if (typeof options[0] === "number") {
          return Number(data);
        } else if (typeof options[0] === "boolean") {
          return data === "true" ? true : false;
        } else {
          return data;
        }
      }
      if (tag === "radio" || tag === "select") {
        if (typeof options[0].value === "number") {
          return Number(data);
        } else if (typeof options[0].value === "boolean") {
          return data === "true" ? true : false;
        } else {
          return data;
        }
      }
      if (tag === "cascader") {
        let keys = data.split(",");
        if (typeof options[0].value === "number") {
          return keys.map((item) => {
            return Number(item);
          });
        } else if (typeof options[0].value === "boolean") {
          return keys.map((item) => {
            return data === "true" ? true : false;
          });
        }
        return keys;
      }
      return data;
    },
    //判断是否是json
    isJson(str) {
      if (typeof str === "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj === "object" && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          return false;
        }
      }
    },
    //时间戳转日期时间
    getDateTime(time) {
      if (!time) return "";
      let date = new Date(time);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      return `${year}-${month < 10 ? "0" : ""}${month}-${
        day < 10 ? "0" : ""
      }${day} ${hour < 10 ? "0" : ""}${hour}:${
        minute < 10 ? "0" : ""
      }${minute}:${second < 10 ? "0" : ""}${second}`;
    },
    // 关闭excel导入组件弹框
    closeDialog(data) {
      this.showImportDialog = false;
    },
    // 子表单编辑时弹窗模式
    subFormConfirm(subForm) {
      const { tableIndex, curRowNum } = subForm;
      const keys = Object.keys(subForm);
      const _this = this;
      let tempObj = {};
      let curTableComp = _this.formConfCopy.fields[tableIndex];
      if (_this.tableAddFlag === "editFlag") {
        keys.forEach((key) => {
          if (key !== "tableIndex" && key !== "curRowNum") {
            _this.formConfCopy.fields[tableIndex].tableData[curRowNum][key] =
              subForm[key];
          }
        });
      }
      if (_this.tableAddFlag === "addFlag") {
        delete subForm.tableIndex;
        delete subForm.curRowNum;
        subForm.showComp = true;
        _this.formConfCopy.fields[tableIndex].tableData.push(subForm);
      }
      _this.showSubDialog = false;
      //  新增之后大于当前页则跳转下一页
      if (curTableComp.__config__.isPage) {
        const num =
          curTableComp.__config__.curPage * curTableComp.__config__.pageSize;
        if (curTableComp.tableData.length > num) {
          _this.formConfCopy.fields[tableIndex].__config__.curPage += 1;
        }
      }
    },
    // 查找是第几个表格
    getModelTableIndex(renderKey) {
      for (let x = 0; x < this.formConfCopy.fields.length; x++) {
        const item = this.formConfCopy.fields[x];
        if (item.__config__.renderKey === renderKey) {
          // return this.tableIndexTest
        }
        if (item.__config__.tag === "Subform") {
          // this.tableIndexTest++
        }
      }
    },
    // 通过renderKey获取到当前表单的对应 子表单
    getIRagIndex(renderKey) {
      let IndexM;
      this.formConfCopy.fields.forEach((item, index) => {
        if (
          item.__config__.tag === "Subform" &&
          item.__config__.renderKey === renderKey
        ) {
          IndexM = index;
        }
      });
      return IndexM;
    },
    // 子表单分页事件
    curPageChange(page, renderKey) {
      const index = this.getIRagIndex(renderKey);
      this.formConfCopy.fields[index].__config__.curPage = page;
    },
    curSizeChange(pageSize, renderKey) {
      const index = this.getIRagIndex(renderKey);
      this.formConfCopy.fields[index].__config__.pageSize = pageSize;
    },
    // 子表单操作列按钮事件
    optionBtnFunc(type, scope, renderKey, editType) {
      const index = this.getIRagIndex(renderKey);
      console.table(this.formConfCopy.fields[index].tableData);
      if (type === "del") {
        //行内删
        this.formConfCopy.fields[index].tableData.splice(scope.$index, 1);
      } else if (type === "copyData") {
        // 深拷贝防止key值变更导致数据错乱
        const copyList = deepClone(this.formConfCopy.fields[index].tableData);
        copyList.splice(scope.$index, 0, scope.row);
        this.formConfCopy.fields[index].tableData = [...copyList];
      } else if (type === "moveUp") {
        if (scope.$index === 0) return;
        this.formConfCopy.fields[index].tableData.splice(scope.$index, 1);
        this.formConfCopy.fields[index].tableData.splice(
          scope.$index - 1,
          0,
          scope.row
        );
      } else if (type === "moveDown") {
        if (
          scope.$index + 1 ===
          this.formConfCopy.fields[index].tableData.length
        )
          return;
        this.formConfCopy.fields[index].tableData.splice(scope.$index, 1);
        this.formConfCopy.fields[index].tableData.splice(
          scope.$index + 1,
          0,
          scope.row
        );
      } else if (type === "edit") {
        if (editType === "table") {
          this.formConfCopy.fields[index].tableData[
            scope.$index
          ].showComp = true;
        } else {
          this.curRowCompData = [];
          this.tableIndex = index;
          this.tableAddFlag = "editFlag";
          this.curRowCompConfig = this.formConfCopy.fields[index].__config__;
          const children =
            this.formConfCopy.fields[index].__config__.children[0]?.__config__
              .children;
          this.curRowNum = scope.$index;
          children.forEach((item) => {
            const newItem = {
              ...item,
              __config__: {
                ...item.__config__,
                defaultValue: scope.row[item.__vModel__],
              },
            };
            this.curRowCompData.push(newItem);
          });
          this.showSubDialog = true;
        }
      }
    },
    // 子表单按钮事件
    btnFunc(type, renderKey, data, editType) {
      const index = this.getIRagIndex(renderKey);
      if (type === "insert") {
        const index = this.getIRagIndex(renderKey);
        if (editType === "table") {
          const config = this.formConfCopy.fields[index].__config__;
          const list = this.formConfCopy.fields[
            index
          ].__config__.children[0].__config__.children.map((cur) => {
            return cur.__vModel__;
          });
          const obj = {};
          list.forEach((item) => {
            (obj[item] = ""), (obj.showComp = true), (obj.id = Date.now());
          });
          this.formConfCopy.fields[index].tableData.push(obj);
          //  新增之后大于当前页则跳转下一页
          if (this.formConfCopy.fields[index].__config__.isPage) {
            const num =
              this.formConfCopy.fields[index].__config__.curPage *
              this.formConfCopy.fields[index].__config__.pageSize;
            if (this.formConfCopy.fields[index].tableData.length > num) {
              this.formConfCopy.fields[index].__config__.curPage += 1;
            }
          }
        } else {
          this.curRowNum = 0;
          this.curRowCompData = [];
          this.tableIndex = index;
          this.tableAddFlag = "addFlag";
          this.curRowCompConfig = this.formConfCopy.fields[index].__config__;
          const children =
            this.formConfCopy.fields[index].__config__.children[0]?.__config__
              .children;
          children.forEach((item) => {
            const newItem = {
              ...item,
              __config__: {
                ...item.__config__,
                defaultValue: "",
              },
            };
            this.curRowCompData.push(newItem);
          });
          this.showSubDialog = true;
        }
      } else if (type === "del") {
        if (data.length === 0) {
          return this.$message.warning("请选择数据");
        }
        const mulArr = data.map((item) => item.id);
        let newArr = this.formConfCopy.fields[index].tableData.filter(
          (item) => mulArr.indexOf(item.id) === -1
        );
        this.formConfCopy.fields[index].tableData = [...newArr];
      } else if (type === "import") {
        if (window.location.pathname.indexOf("/formdesign") !== -1) {
          return this.$message.warning("预览不支持数据导入");
        }
        this.showImportDialog = true;
        this.tableIndex = index;
        this.curformName = this.formConfCopy.fields[index].__config__.label;
        this.subFormId = this.formConfCopy.fields[index].__vModel__;
      } else if (type === "export") {
        if (window.location.pathname.indexOf("/formdesign") !== -1) {
          return this.$message.warning("预览不支持数据导出");
        }
        if (this.formConfCopy.fields[index].tableData.length === 0) {
          return this.$message.warning("请先添加数据");
        }
        this.getTagIcons(
          this.formConfCopy.fields[index].__config__.children[0].__config__
            .children
        );
        const tableName = this.formConfCopy.fields[index].__config__.label;
        const fields = this.formConfCopy.fields[
          index
        ].__config__.children[0].__config__.children.map((item) => {
          return {
            name: item.__vModel__,
            desc: item.__config__.label,
          };
        });
        // 导出
        exportToExcel(
          fields,
          this.tableTagIcons,
          tableName,
          this.formConfCopy.fields[index].tableData
        );
      }
    },
    //获取所有字段的tag、dataType、option
    async getTagIcons(data) {
      if (data.length === 0) return;
      let comps = data.filter((item) => {
        return item.__config__.tag !== "TitleLine";
      });
      for (let i = 0; i < comps.length; i++) {
        let item = comps[i];
        if (
          item.__config__.tag === "el-card" ||
          item.__config__.tag === "el-tabs" ||
          item.__config__.tag === "Steps" ||
          item.__config__.tag === "el-collapse"
        ) {
          let tem = item.__config__.children.map((c) => {
            getTagIcons(c.__config__.children);
          });
        } else {
          let tag = item.__config__.tagIcon;
          let options = [];
          if (tag === "switch") {
            options = [item["active-value"], item["inactive-value"]];
            this.tableTagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options],
            });
          } else if (["select", "radio", "checkbox"].includes(tag)) {
            if (item.dataType === "static") {
              options = item.options;
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options],
              });
            } else if (item.dataType === "dictionary" && item.dictName !== "") {
              let res = await getDictData({
                dictType: item.dictName,
              });
              if (res.code === 0) {
                res.data.forEach((item) => {
                  options.push({
                    label: item.label,
                    value: item.label,
                  });
                });
              }
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options],
              });
            } else if (
              item.dataType === "datasource" &&
              item.tableName !== "" &&
              item.fieldName !== ""
            ) {
              let res = await getColumnData({
                tableName: item.tableName,
                column: item.fieldName,
              });
              if (res.code === 0) {
                res.data.forEach((item) => {
                  options.push({
                    label: item,
                    value: item,
                  });
                });
              }
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options],
              });
            }
          } else if (tag === "cascader" || tag === "tree-table") {
            if (item.dataType === "dynamic") {
              await getDynamicOptions(item.fields, item.formName).then(
                (res) => {
                  options = res;
                }
              );
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options],
              });
            } else if (item.dataType === "static") {
              options = item.options;
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: [...options],
              });
            } else if (item.dataType === "region") {
              this.tableTagIcons.push({
                tag: tag,
                dataType: item.dataType,
                option: regionData,
              });
            }
          } else {
            this.tableTagIcons.push({
              tag: tag,
              dataType: item.dataType,
              option: [...options],
            });
          }
        }
      }
    },
    // 更新表格行的值
    async updateTableData() {
      const { index, compObj, value, renderKey } = arguments[0];
      const curTableIdx = this.getIRagIndex(renderKey);
      this.formConfCopy.fields[curTableIdx].tableData[index][
        compObj.__vModel__
      ] = value;
      // 数据联动(判断是否需要联动)
      if (this.linkNameMap.has(compObj.__vModel__)) {
        const objList = [];
        this.linkObjList.forEach((item) => {
          let obj = {};
          if (item.curParams === compObj.__vModel__) {
            obj = {
              linkName: item.linkName,
              linkValueName: item.linkValueName,
              tableName: item.tableName,
              curValue: Array.isArray(value) ? value.toString() : value,
              returnField: item.returnField,
            };
            objList.push(obj);
          }
        });
        // 联动数据
        const res = await getLinkData(objList);
        if (res.code === 0) {
          if (Array.isArray(res.data)) {
            res.data.forEach((valueObj) => {
              this.loopSearch(this.formConfCopy.fields, valueObj);
              // this.formConfCopy.fields[curTableIdx].tableData[index][valueObj.key] = valueObj.value
            });
          }
        }
      }
      // 公式计算
      const tableComp =
        this.formConfCopy.fields[curTableIdx].__config__.children[0].__config__
          .children;
      tableComp.forEach((comp) => {
        let editorStr = comp.__config__.formulaStr;
        if (editorStr) {
          const signList = editorStr.match(/\$.*?\#/g);
          if (signList?.length > 0) {
            const otherStr = editorStr.split(/\$.*?\#/g);
            let exsitFlag = false;
            let valueList = [];
            signList.forEach((signField) => {
              // 取出字段field
              let fieldValue;
              const field = signField.slice(1, signField.length - 1).trim();
              const curVal =
                this.formConfCopy.fields[curTableIdx].tableData[index][field];
              if (curVal && curVal !== "-") {
                fieldValue = curVal;
              } else {
                fieldValue = 0;
              }
              valueList.push(fieldValue);
            });
            editorStr = this.joinStr(otherStr, valueList);
          }
          // 调用计算
          const finallyValue = calculate(editorStr);
          // 塞值
          this.formConfCopy.fields[curTableIdx].tableData[index][
            comp.__vModel__
          ] = finallyValue;
        }
      });
    },
    makeTable(newKey) {
      let IndexM;
      this.formConfCopy.fields.forEach((item, index) => {
        if (
          item.__config__.tag === "Subform" &&
          newKey === item.__config__.renderKey
        ) {
          IndexM = index;
        }
      });
      const childrenCopy = deepClone(
        this.formConfCopy.fields[IndexM].__config__.children[0].__config__
          .children
      );
      return childrenCopy;
    },
    // 列显隐
    explicit(renderKey) {
      this.$emit("click", renderKey);
    },
    // 子表单选中行事件
    handleSelectionChange(val) {
      this.mulArr = [...val];
    },
    //初始化表单规则配置，构造接口所需参数（目前只处理一条规则，后续多条规则需根据后端接口参数要求进行修改）
    initRuleConfig(formConfCopy, ruleConfig, formData) {
      if (formConfCopy.ruleConfig && formConfCopy.ruleConfig.length > 0) {
        // formConfCopy.ruleConfig.sort((a,b) => {return a.basic.order-b.basic.order}).forEach((rule,index) => {
        formConfCopy.ruleConfig.forEach((cur) => {
          let rule = {};
          rule.sysFieldRulesListVo = [];
          rule.formList = [];
          // rule.batch = cur.basic.order
          cur.formrule.forEach((r, ind) => {
            rule.hiddenField = cur.hide.join(",");
            rule.dispalyField = cur.show.join(",");
            rule.onlyDisplay = cur.onlyDisplay;
            rule.onlyHidden = cur.onlyHidden;
            let list = [];
            r.rules.forEach((item, index) => {
              list.push({
                ruleFiledName: item.fieldName,
                ruleValue: item.content,
                sumFiled: item.compare,
                relat: index > 0 ? r.method[index - 1] : "",
              });
            });
            rule.sysFieldRulesListVo.push({
              relat: ind > 0 ? cur.method[ind - 1] : "",
              sysFieldRuleVo: list,
            });
          });
          Object.keys(formData).forEach((key) => {
            //获取表单初始各个字段的值
            rule.formList.push({
              filedName: key,
              value: Array.isArray(formData[key])
                ? formData[key].join(",")
                : formData[key],
            });
          });
          ruleConfig.push(rule);
        });
        // })
        getFormRule(ruleConfig)
          .then((res) => {
            if (res.code === 0) {
              if (res.data && res.data !== "不符合规则") {
                //符合规则
                this.displayFields = res.data.dispalyField?.split(",") || [];
                this.changeShowHide(formConfCopy.fields, this.displayFields);
              }
              //  else { //不符合规则
              //     this.displayFields = []
              //     this.changeShowHide(formConfCopy.fields,this.displayFields)
              // }
            }
          })
          .catch((e) => console.log(e));
      }
    },
    //根据表单规则更改字段显隐
    changeShowHide(componentList, display) {
      componentList.forEach((cur, index) => {
        if (display.includes(cur.__vModel__)) {
          this.$set(cur, "hide", false);
        } else {
          this.$set(cur, "hide", true);
        }
        if (cur.__config__.children)
          this.changeShowHide(cur.__config__.children, display);
      });
    },
    // 初始化赋值操作
    async initFormData(componentList, formData) {
      componentList.forEach(async (cur, index) => {
        const config = cur.__config__;
        if (config.tag === "Subform") {
          // this.initFormData(config.children[0].__config__.children, formData)
          formData[cur.__vModel__] = [];
          config.children[0].__config__.children.forEach((xxyy, idx) => {
            formData[cur.__vModel__][idx] = {
              ...formData[cur.__vModel__][idx],
            };
            if (xxyy.__vModel__)
              formData[cur.__vModel__][idx][xxyy.__vModel__] =
                config.defaultValue || "";
          });
          cur.tableData = cur.tableData || [];
          cur.tableData = cur.tableData.map((curRow) => {
            return {
              id: parseInt(Math.random() * 10000 + Date.now()),
              ...curRow,
            };
          });
        } else {
          if (config.tagIcon === "date" && cur.isLimit) {
            //如果是日期选择 并且限制选择范围
            cur["picker-options"].disabledDate = function (time) {
              return (
                time.getTime() > cur["picker-options"].maxDate ||
                time.getTime() < cur["picker-options"].minDate - 8.64e7
              ); // 设
            };
          }
          if (config.tagIcon === "time-range" && cur.isLimit) {
            //如果是时间范围 并且限制选择范围
            let arr = [];
            arr.push(cur["picker-options"].selectableRange);
            cur["picker-options"].selectableRange = arr;
          }
          // 适配数据可能为数字 0 的情况
          if (cur.bianma && this.status === "edit") {
            encodeCode = cur.rulesSelectValue;
          }
          config.defaultValue =
            this.originData[cur.__vModel__] ||
            this.originData[cur.__vModel__] === 0
              ? this.originData[cur.__vModel__]
              : config.defaultValue;
          if (cur.bianma && !this.codeNameid && this.status === "add") {
            encodeCode = cur.rulesSelectValue;
            let params = {
              tableName: this.tableName,
              column: cur.__vModel__,
              encodeId: cur.rulesSelectValue,
            };
            await getAutomaticCode(params).then((res) => {
              if (res.code === 0) {
                // cur.disabled = true
                // cur.__config__.defaultValue = res.data.storeData === "null"?' ':res.data.storeData
                // formData[cur.__vModel__] = cur.__config__.defaultValue
                cur.__config__.defaultValue =
                  res.data.storeData === "null" ? " " : res.data.storeData; //展示隐藏值
                cur.__slot__.options = [
                  {
                    label: res.data.showData,
                    value: res.data.storeData,
                  },
                ];
                cur.options = [
                  {
                    label: res.data.showData,
                    value: res.data.storeData,
                  },
                ];
                cur.value = cur.__config__.defaultValue;
                this.$set(
                  this[this.formConf.formModel],
                  cur.__vModel__,
                  cur.__config__.defaultValue
                );
              }
            });
          }
          if (cur.bianma && this.status !== "add") {
            console.log(this.codeReshow);
            cur.options = [this.codeReshow];
            cur.__slot__.options = [this.codeReshow];
          }
          if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue;
          if (config.tag === "el-upload") {
            //上传组件文件列表赋值
            cur["file-list"] = config.defaultValue ? config.defaultValue : [];
          }
          if (config.children) this.initFormData(config.children, formData);
        }
      });
    },
    //构建表单校验规则
    buildRules(componentList, rules) {
      componentList.forEach((cur) => {
        const config = cur.__config__;
        if (Array.isArray(config.regList)) {
          if (config.required) {
            const required = {
              required: config.required,
              message: cur.placeholder,
            };
            if (Array.isArray(config.defaultValue)) {
              required.type = "array";
              required.message = `请至少选择一个${config.label}`;
            }
            required.message === undefined &&
              (required.message = `${config.label}不能为空`);
            config.regList.push(required);
          }
          rules[cur.__vModel__] = config.regList.map((item) => {
            item.pattern && (item.pattern = eval(item.pattern));
            item.validator &&
              (item.validator = eval(item.validator.replace("\n", ""))); //表单设计添加的默认校验规则
            item.trigger = ruleTrigger && ruleTrigger[config.tag];
            return item;
          });
        }
        if (config.children) this.buildRules(config.children, rules);
      });
    },
    //重置
    resetForm() {
      this.formConfCopy = deepClone(this.formConf);
      this.$refs[this.formConf.formRef].resetFields();
      setShowHide.call(this); //更新表单规则
      this.$emit("reset");
    },
    //提交
    async submitForm() {
      this.objMonitorCopy = this.objMonitor;
      if (this.formConf.formJs && this.formConf.formJs.beforeSubmit) {
        try {
          await bindEventScript.call(
            this,
            "",
            "",
            this.formConf.formJs.beforeSubmit
          );
        } catch (error) {
          console.log("parse event script error, ", error);
          return;
        }
      }
      //  if(this.formConf.formJs && this.formConf.formJs.beforeSubmit){
      //     const result = bindEventScript.call(this,'','',this.formConf.formJs.beforeSubmit);
      //     if (result) {
      //       return
      //     }
      // }
      if (isHasCode) {
        //有编码字段时才会走接口
        if (this.status === "add") {
          let params = {
            tableName: this.tableName,
            column: encodeobj.__vModel__,
            encodeId: encodeobj.rulesSelectValue,
            monitorMap: objMonitor,
          };
          await getAutomaticCode(params).then((res) => {
            if (res.code === 0) {
              encodeobj.__config__.defaultValue =
                res.data.storeData === " " ? " " : res.data.storeData; //展示隐藏值
              encodeobj.__slot__.options = [
                {
                  label: res.data.showData,
                  value: res.data.storeData,
                },
              ];
              encodeobj.options = [
                {
                  label: res.data.showData,
                  value: res.data.storeData,
                },
              ];
              encodeobj.value = encodeobj.__config__.defaultValue;
              this.$set(
                this[this.formConf.formModel],
                encodeobj.__vModel__,
                encodeobj.__config__.defaultValue
              );
            }
          });
        } else if (this.status === "edit") {
          // 1、判断数据是否有变化，无变化直接提交
          // 2、有变化，重新调接口获取数据
          let changeListen = false;
          this.formConfCopy.fields.forEach((item, index) => {
            if (item.__vModel__ === listenField) {
              if (item.__config__.defaultValue !== originAllData[listenField]) {
                changeListen = true;
              }
            }
          });
          if (changeListen) {
            let params = {
              tableName: this.tableName,
              column: encodeobj.__vModel__,
              encodeId: encodeobj.rulesSelectValue,
              monitorMap: objMonitor,
            };
            await getAutomaticCode(params).then((res) => {
              if (res.code === 0) {
                encodeobj.__config__.defaultValue =
                  res.data.storeData === " " ? " " : res.data.storeData; //展示隐藏值
                encodeobj.__slot__.options = [
                  {
                    label: res.data.showData,
                    value: res.data.storeData,
                  },
                ];
                encodeobj.options = [
                  {
                    label: res.data.showData,
                    value: res.data.storeData,
                  },
                ];
                encodeobj.value = encodeobj.__config__.defaultValue;
                this.$set(
                  this[this.formConf.formModel],
                  encodeobj.__vModel__,
                  encodeobj.__config__.defaultValue
                );
              }
            });
          }
        }
      }
      await this.$refs[this.formConf.formRef].validate((valid) => {
        if (!valid) return false;
        // 触发 submit 事件
        this.$nextTick(() => {
          if (window.location.pathname.indexOf("/formdesign") !== -1) {
            return this.$message.warning("功能预览不支持数据提交");
          }
          let tableValueMap = new Map();
          // 存储所有子表单的字段name
          const fieldNameList = [];
          let allRightFlag = true;
          for (let x = 0; x < this.formConfCopy.fields.length; x++) {
            let cur = this.formConfCopy.fields[x];
            if (cur.__config__.tag === "Subform") {
              for (
                let y = 0;
                y < cur.__config__.children[0].__config__.children.length;
                y++
              ) {
                let child = cur.__config__.children[0].__config__.children[y];
                if (child.__config__.required && cur.tableData.length === 0) {
                  this.$message.error(`请添加${cur.__config__.label}数据`);
                  return;
                }
                fieldNameList.push(child.__vModel__);
              }
              // 子表单校验
              this.$refs[cur.__config__.renderKey].validate((res) => {
                if (!res) {
                  allRightFlag = false;
                }
              });
            }
          }
          
          const stepList =  this.formConfCopy.fields.filter((_) => _.__config__.tag === 'Steps')
          if(stepList.length > 0){ //如果有步骤条
            stepList[0].__config__.children.map((item) => {
              item.__config__.children.map((itemChild) => {
                if(itemChild.__config__.required && !itemChild.__config__.defaultValue){
                  this.$message.error(`请添加${itemChild.__config__.label}数据`);
                  allRightFlag =false
                  return;
                } 
              })
            })
          }
          if (allRightFlag) {
            this.formConfCopy.fields.forEach((cur) => {
              if (cur.__config__.tag === "Subform") {
                cur.tableData.forEach((item) => {
                  const keys = Object.keys(item);
                  for (let a = keys.length - 1; a >= 0; a--) {
                    const ele = keys[a];
                    if (!fieldNameList.includes(ele)) {
                      delete item[ele];
                    }
                  }
                });
                tableValueMap.set(cur.__vModel__, cur.tableData);
              }
            });
            this.$emit("loadingPae");
            this.$emit("submit", this[this.formConf.formModel], tableValueMap);
          }
          return true;
        });
      });
    },
    //保存表单,存到草稿，暂不使用
    saveForm() {
      this.$refs[this.formConf.formRef].validate((valid) => {
        if (!valid) return false;
        if (this.$store.state.currentStep.step < child.length - 1)
          this.$store.commit("DOWN");
        this.$emit("save", this[this.formConf.formModel]);
        return true;
      });
    },
    //取消
    cancelForm() {
      this.$emit("cancel");
    },
    //为el-upload绑定一个on-success、on-remove事件，并将返回值返回给表单
    bindUploadSuccess(fields, target) {
      fields &&
        fields.map((item) => {
          if (item.action) {
            item.action = `${process.env.VUE_APP_BASE_API}/admin-api/infra/file/upload`;
            item.headers = { Authorization: "Bearer " + getAccessToken() };
            item["on-success"] = (res, file, fileList) => {
              this[target][item.__vModel__] = fileList.map((item) => {
                let temp = {
                  name: "",
                  url: "",
                };
                if (item.response) {
                  temp.name = item.name;
                  temp.url = item.response.data;
                  return temp;
                } else {
                  temp.name = item.name;
                  temp.url = item.url;
                  return temp;
                }
                //  return item.response?item.response:item
              });
              item["file-list"] = this[target][item.__vModel__];
            };
            item["on-remove"] = (file, fileList) => {
              this[target][item.__vModel__] = fileList.map((item) => {
                let temp = {
                  name: "",
                  url: "",
                };
                if (item.response) {
                  temp.name = item.name;
                  temp.url = item.response.data;
                  return temp;
                } else {
                  temp.name = item.name;
                  temp.url = item.url;
                  return temp;
                }
                // return item.response?item.response:item
              });
              item["file-list"] = this[target][item.__vModel__];
            };
            item["on-preview"] = (file) => {
              const nameSplitList = file.name.split(".");
              const type = nameSplitList[nameSplitList.length - 1];
              if (["jpeg", "jpg", "png", "PNG"].includes(type)) {
                window.open(file.url, "_blank");
              } else {
                download(file.url, file.name);
              }
            };
          }
          if (
            ["el-card", "el-tabs", "Steps", "el-collapse", "Subform"].includes(
              item.__config__.tag
            )
          ) {
            item.__config__.children.map((data) => {
              this.bindUploadSuccess(data.__config__.children, target);
            });
          }
        });
    },
    closeTableDialog(obj) {
      this.showImportDialog = false;
      if (obj.flag) {
        obj.data.forEach((item) => {
          this.formConfCopy.fields[this.tableIndex].tableData.push(item);
        });
      }
    },
    updateSubmitData() {
      if (this.formConf?.formJs?.afterSubmit) {
        bindEventScript.call(this, "", "", this.formConf.formJs.afterSubmit);
      }
    },
  },
  render(h) {
    return (
      <div class="parserFormClass">
        {this.showSubDialog && (
          <SubFormEditDialog // 子表单弹框填写数据
            on-confirm={(subForm) => {
              this.subFormConfirm(subForm);
            }}
            curRowNum={this.curRowNum}
            curRowCompData={this.curRowCompData}
            config={this.curRowCompConfig}
            tableIndex={this.tableIndex}
            on-cancel={() => (this.showSubDialog = false)}
          ></SubFormEditDialog>
        )}
        {this.showImportDialog && ( // 数据导入弹框
          <TableDataImportDialog
            curFormId={this.subFormId}
            curFormName={this.curformName}
            tableFlag="Subform"
            on-closeDialog={(obj) => this.closeTableDialog(obj)}
          ></TableDataImportDialog>
        )}
        {renderFrom.call(this, h)}
      </div>
    );
  },
};
</script>
<style lang="less" scoped>
.cardhover {
  box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0);
}
.cardhover:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/deep/.el-step__title {
  cursor: pointer !important;
}
.parserFormClass {
  /deep/ .el-input.is-disabled .el-input__inner {
    color: black;
    border: none;
    // max-width:1200px;
  }
  /deep/ .el-textarea.is-disabled .el-textarea__inner {
    color: black;
  }
  /deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background-color: #1890ff;
  }
  /deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
    background-color: white;
  }
  /deep/ .el-radio.is-disabled.is-checked {
    /deep/ .el-radio__input.is-disabled + span.el-radio__label {
      color: #1890ff;
    }
    .el-radio__label {
      color: #1890ff;
    }
  }
  /deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #1890ff;
  }
  /deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: white;
  }
  /deep/ .el-checkbox.is-disabled.is-checked {
    /deep/ .el-checkbox__input.is-disabled + span.el-checkbox__label {
      color: #1890ff;
    }
    .el-checkbox__label {
      color: #1890ff;
    }
  }
  /deep/ .el-input.el-input--medium.is-disabled.el-input--suffix {
    /deep/ .el-input.is-disabled .el-input__inner {
      border: none;
    }
  }
  /deep/ .el-textarea.is-disabled .el-textarea__inner {
    border: none;
  }
  /deep/ .el-range-editor.is-disabled {
    border: none;
  }
  /deep/ .el-range-editor.is-disabled input {
    color: black;
  }
  /deep/ .el-range-editor.is-disabled .el-range-separator {
    color: black;
  }
  /deep/
    .el-input.el-input--small.is-disabled.el-input-group.el-input-group--append.el-input--suffix {
    /deep/ .el-input-group__append {
      border: none;
    }
    /deep/ .el-button.el-button--primary.el-button--medium.is-disabled {
      /deep/ .fa-map-marker:before {
        content: "";
      }
    }
  }
}
</style>
